<template>
  <el-dialog
    v-el-drag-dialog="{updataFull, updataDialogWidth}"
    :fullscreen="isfullscreen"
    :title="rowData.cableName + $t('FIBER_CORE')"
    :visible="visible"
    :width="setDialogWidth('1000px')"
    @close="close"
    @open="open"
  >
    <div class="p-10 pt-0 flex align-center justify-end">
      <!-- <div>{{ $t('CABLE_NAME') }}：{{ rowData.cableName }}</div> -->
      <div class="flex align-center">
        <el-button
          slot="trigger"
          class="ml-10"
          size="mini"
          type="primary"
          @click="importVisible = true"
        >{{ $t('IMPORT') }}</el-button>
        <el-button class="ml-10" size="mini" @click="exportClick">
          {{ $t('EXPORT') }}
        </el-button>
      </div>
    </div>
    <el-form
      ref="ruleForm"
      :model="formData"
      label-width="0"
      class="flex flex-wrap"
    >
      <el-form-item
        v-for="(item, index) in portList"
        :key="item.id"
        class="item-width"
        :label="index + 1 < 10 ? `0${index + 1}` : `${index + 1}`"
        label-width="40px"
      >
        <el-input v-model="item.fiberName" clearable maxlength="32" />
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button @click="close">{{ $t('CANCEL') }}</el-button>
      <el-button type="primary" @click="$debounce(savePort)">{{
        $t('SAVE')
      }}</el-button>
    </div>
    <!--导入引导-->
    <import-boot
      :visible="importVisible"
      @exportClick="exportClick"
      @ImportClick="importClick"
      @import-close="importVisible = false"
    >
      <template #notice>
        {{ $t('BEFORE_IMPORTING_PLEASE') }}
        <span class="exportClick" @click="exportClick">
          {{ $t('EXPORT_TEMPLATE') }}
        </span>
        {{ $t('ALL_PORT_INFORMATION') }}
      </template>
    </import-boot>
  </el-dialog>
</template>

<script>
  import { mapGetters } from 'vuex'
  import { importExcel, exportExcel } from '@/utils/jsonToExcel'
  import cableFiberApi from '@/api/oen/CableFiberApi'
  import ImportBoot from '@/components/ImportBoot'
  import { deepClone } from '@/utils/common'
  import OperateLogApi from '@/api/system/OperateLogApi.js'
  export default {
    name: 'DeviceConfigPortOpticalCable',
    components: { ImportBoot },
    props: {
      visible: {
        type: Boolean,
        default: false
      },
      rowData: {
        type: Object,
        default: () => {}
      }
    },
    data() {
      return {
        formData: {},
        portList: [],
        importVisible: false
      }
    },
    computed: {
      ...mapGetters(['getUserId', 'getUser'])
    },
    methods: {
      exportClick() {
        const sheets = []
        const sheetNames = []
        const arr = []
        this.portList.forEach((item, index) => {
          const eq = index + 1
          const num = eq < 10 ? '0' + eq : eq + ''
          const portItem = {
            [this.$t('PORT_NUMBER')]: num,
            ID: item.fiberId,
            [this.$t('FIBER_NAME')]: item.fiberName
          }
          arr.push(portItem)
        })
        sheets.push(arr)
        sheetNames.push(`sheet-${this.rowData.cableName}`)
        exportExcel(
          sheets,
          `${this.rowData.cableName}${this.$t('FIBER_CORE')}${this.$t(
            'PORT_EXPORT'
          )}`,
          sheetNames
        )
        // 记录导出日志
        this.addLog('export')
      },
      importClick(file) {
        importExcel(file).then((res) => {
          console.log(res)
          const portList = deepClone(this.portList)
          const data = res.data
          const dataList = []
          const allValue = []
          const duplicateValue = []
          data.forEach(item => {
            const values = Object.values(item)
            const val = values[2] + ''
            dataList.push({ [values[1]]: val })
            // 查重端口名称
            if (allValue.includes(val)) {
              duplicateValue.push(val)
            }
            allValue.push(val)
          })
          console.log('allValue', allValue)
          console.log('duplicateValue', duplicateValue)
          if (duplicateValue.length) {
            this.$message.error(
              this.$t('DUPLICATE_PORT_NAME', {
                msg1: this.$t('FIBER_CORE'),
                msg2: duplicateValue.join(),
                msg3: this.$t('IMPORT')
              })
            )
            return
          }
          if (file.name.includes(this.rowData.cableName)) {
            portList.forEach((item, index) => {
              for (let i = 0; i < dataList.length; i++) {
                const keys = Object.entries(dataList[i])
                if (keys[0][0] === item.fiberId) {
                  item.fiberName = keys[0][1]
                  break
                }
              }
            })
            this.portList = portList
            this.importVisible = false
            // 记录导入日志
            this.addLog('import')
          } else {
            this.$message.error(
              `${this.$t('PLEASE_UPLOAD_NODE')}${
                this.rowData.cableName
              }${this.$t('TEMPLATE_FILE')}`
            )
          }
        })
      },
      open() {
        cableFiberApi
          .listByCableId({ cableId: this.rowData.cableId })
          .then((res) => {
            if (res) {
              this.portList = res
            } else {
              this.$message.error(res.msg)
            }
          })
      },
      close() {
        this.$emit('close')
      },
      // 纤芯编辑保存
      savePort() {
        const allValue = []
        const duplicateValue = []
        this.portList.forEach((i) => {
          // 查重端口名称
          if (allValue.includes(i.fiberName)) {
            duplicateValue.push(i.fiberName)
          }
          allValue.push(i.fiberName)
        })
        if (duplicateValue.length) {
          this.$message.error(
            this.$t('DUPLICATE_PORT_NAME', {
              msg1: this.$t('FIBER_CORE'),
              msg2: duplicateValue.join(),
              msg3: this.$t('SAVE')
            })
          )
          return
        }
        const requestData = this.portList.map((i) => {
          return {
            id: i.id,
            fiberName: i.fiberName
          }
        })
        if (requestData.some((i) => String(i.fiberName).trim() === '')) {
          this.$message.error(this.$t('NO_FIBER_NAME'))
          return
        }
        cableFiberApi.batchUpdate(requestData, { cableName: this.rowData.cableName }).then((res) => {
          if (res) {
            this.close()
            this.$message.success(this.$t('SAVE_SUCCESS'))
          } else {
            this.$message.error(res.msg)
          }
        })
      },
      addLog(action, result = true) {
        const params = {
          api: '',
          item: 'MENU_CABLE_MANAGER', // 光缆管理
          terminal: action === 'export' ? 'EDIT_FIBRE_EXPORT' : 'EDIT_FIBRE_IMPORT',
          object: this.rowData.cableName,
          operateResult: result,
          realName: this.getUser.realName,
          content: JSON.stringify({
            cableName: this.rowData.cableName,
            currentUserId: this.getUserId,
            i18nKey: action === 'export' ? 'EDIT_FIBRE_EXPORT_LOG' : 'EDIT_FIBRE_IMPORT_LOG'
          })
        }
        // 记录登录日志
        OperateLogApi.addLog(params)
      }
    }
  }
</script>
<style scope>
  .item-width {
    width: 120px;
  }
</style>
